std::condition

您所在的位置:网站首页 condition variable predicate std::condition

std::condition

2024-07-06 06:54| 来源: 网络整理| 查看: 265

本篇介紹 C++ 的 std::condition_variable 用法,使用 std::condition_variable 的 wait 會把目前的執行緒 thread 停下來並且等候事件通知,而在另外一個執行緒裡我們可以使用 std::condition_variable 的 notify_one 或 notify_all 去發送通知那些正在等待的事件,這在多執行绪程式裡經常使用到,以下將開始介紹 std::condition_variable 的用法,並展示一些範例,建議閱讀以下文章前需先對建立 std::thread 多執行緒與std::mutex 鎖有一定程度的熟悉。

需要引入的標頭檔:

以下為 condition_variable 常用的成員函式與說明,wait:阻塞當前執行緒直到條件變量被喚醒notify_one:通知一個正在等待的執行緒notify_all:通知所有正在等待的執行緒

使用 std::condition_variable 的 wait 必須要搭配 std::unique_lock 一起使用。

範例1. 用 notify_one 通知一個正在 wait 的執行緒

下面的例子是先開一個新的執行緒 worker_thread 然後使用 std::condition_variable 的 wait 事件的通知,此時 worker_thread 會阻塞(block)直到事件通知才會被喚醒,之後 main 主程式延遲個 5 ms 在使用 std::condition_variable 的 notify_one 發送,之後 worker_thread 收到 來自主執行緒的事件通知就離開 wait 繼續往下 cout 完就結束該執行緒,

這裡主程式的延遲 5ms 是避免一開始執行緒還沒建立好來不及 wait 等待通知,主程式就先發送 notify_one 事件通知了,

std-condition_variable.cpp12345678910111213141516171819202122232425262728293031// g++ std-condition_variable.cpp -o a.out -std=c++11 -pthread#include #include #include #include #include std::mutex m;std::condition_variable cond_var;void worker_thread(){ std::unique_lock lock(m); std::cout


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3